package com.xqboss.apps.service.order.pay.impl;

import cn.hutool.core.date.LocalDateTimeUtil;
import com.alibaba.fastjson2.JSON;
import com.alibaba.fastjson2.JSONObject;
import com.xqboss.apps.constant.YeepayConfig;
import com.xqboss.apps.domain.order.PayApply;
import com.xqboss.apps.dto.order.SignPayDto;
import com.xqboss.apps.dto.order.TradeResultDto;
import com.xqboss.apps.service.order.pay.PayExecutor;
import com.xqboss.common.exception.ServiceException;
import com.yeepay.yop.sdk.service.common.request.YopRequest;
import com.yeepay.yop.sdk.service.common.response.YopResponse;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;

import javax.servlet.http.HttpServletRequest;
import java.math.BigDecimal;

@Slf4j
public abstract class BaseYeePay extends PayExecutor {

    @Autowired
    protected YeepayConfig yeepayConfig;

    @Override
    public TradeResultDto verifyCallback(HttpServletRequest request, Object params) {
        String response = (String) params;
        try {
//            parentMerchantNo	发起方商编	String	交易发起方的商编
//            merchantNo	商户编号	String	收款商户编号
//            orderId	商户收款请求号	String	交易下单传入的商户收款请求号
//            uniqueOrderNo	易宝收款订单号	String
//            channelOrderId	渠道订单号	String	该笔订单在微信、支付宝或银行侧系统生成的单号
//            subOrderInfoList	子单信息	String	以Json形式返回
//            orderAmount	订单金额	String	单位:元
//            payAmount	支付金额	String	单位:元商户承担手续费:支付金额=订单金额用户承担手续费:支付金额= 订单金额+手续费金额
//            status	订单状态	String	SUCCESS（订单支付成功）
//            paySuccessDate	支付成功时间	String	例：2021-01-01 00:00:00
//            payWay	支付方式	String	USER_SCAN：用户扫码MERCHANT_SCAN：商家扫码JS_PAY：JS支付MINI_PROGRAM：小程序支付WECHAT_OFFIACCOUNT：微信公众号支付ALIPAY_LIFE：生活号支付FACE_SCAN_PAY：刷脸支付SDK_PAY：SDK支付H5_PAY：H5支付ONEKEYPAY：一键支付BINDCARDPAY：绑卡支付E_BANK：网银支付ENTERPRISE_ACCOUNT_PAY：企业账户支付ACCOUNT_BOOK_PAY: 记帐簿支付
//            channel	渠道类型	String	WECHAT：微信ALIPAY：支付宝UNIONPAY：银联APPLEPAY：苹果支付仅聚合支付返回该参数。
//            payerInfo	付款信息	String
//            realPayAmount	用户实际支付金额	String
//            channelPromotionInfo	渠道侧优惠列表	String
//            ypPromotionInfo	易宝侧优惠列表	String
//            failCode	支付失败的code码	String
//            failReason	支付失败的失败原因	String
//            failCode	支付失败的code码	String
//            failReason	支付失败的失败原因	String
//            terminalInfo	终端信息	String
            JSONObject json = JSON.parseObject(response);
            // 支付订单状态
            String status = json.getString("status");
            if(!"SUCCESS".equals(status)){
                // 正常来说不可能走到这里
                throw new ServiceException("订单状态错误！");
            }
            String parentMerchantNo = json.getString("parentMerchantNo");
            // 商户编号
            String merchantNo = json.getString("merchantNo");
            // 订单金额
            String orderId = json.getString("orderId");
            // 易宝收款订单号
            String uniqueOrderNo = json.getString("uniqueOrderNo");
            // 订单金额
            BigDecimal orderAmount = json.getBigDecimal("orderAmount");
            // 支付金额
            BigDecimal payAmount = json.getBigDecimal("payAmount");
            // 用户实际支付金额
            BigDecimal realPayAmount = json.getBigDecimal("realPayAmount");
            // 付款信息
            String payerInfo = json.getString("payerInfo");
            // 付款渠道
            String channel = json.getString("channel");
            // 支付时间
            String paySuccessDate = json.getString("paySuccessDate");

            TradeResultDto result = new TradeResultDto();
            result.setTradeNo(orderId);
            result.setOutTradeNo(uniqueOrderNo);
            result.setTotalAmount(orderAmount);

//            result.setBuyerId(params.get("buyer_id"));
//            result.setBuyerAccount(params.get("buyer_logon_id"));
//            result.setSellerId(params.get("seller_id"));
//            result.setSellerAccount(params.get("seller_email"));

//            result.setReceiptAmount(new BigDecimal(params.get("receipt_amount")));
            result.setPayAmount(realPayAmount);
            result.setPayTime(LocalDateTimeUtil.parse(paySuccessDate, "yyyy-MM-dd HH:mm:ss"));
            return result;
        } catch (Exception e) {
            log.error("易宝回调异常", e);
            throw new RuntimeException("回调解密失败！");
        }
    }


    @Override
    public TradeResultDto queryTrade(PayApply info) {
        YopRequest request = new YopRequest( "/rest/v1.0/trade/order/query", "GET");
        request.addParameter("parentMerchantNo", yeepayConfig.getMerchantNo());
        request.addParameter("merchantNo", yeepayConfig.getMerchantNo());
        request.addParameter("orderId", info.getId());
        try {
            YopResponse response = yeepayConfig.getClient().request(request);
            JSONObject json = JSON.parseObject(response.getStringResult());
            if("OPR00000".equalsIgnoreCase(json.getString("code"))){
                if("SUCCESS".equalsIgnoreCase(json.getString("status"))){
                    // 支付成功
                    TradeResultDto result = new TradeResultDto();
                    result.setTradeNo(json.getString("orderId"));
    //                result.setBuyerId();
    //                result.setBuyerAccount();
    //                result.setSellerId();
    //                result.setSellerAccount();
                    result.setPayTime(LocalDateTimeUtil.parse(json.getString("paySuccessDate"), "yyyy-MM-dd HH:mm:ss"));
                    result.setPayAmount(json.getBigDecimal("payAmount"));
                    result.setTotalAmount(json.getBigDecimal("orderAmount"));
    //                result.setReceiptAmount();
                    result.setOutTradeNo(json.getString("uniqueOrderNo"));
                    return result;
                }else{
                    throw new ServiceException("订单未支付！");
                }
            }
            log.error("获取支付状态异常：{} - {}", info.getId(), response.getStringResult());
            throw new ServiceException("获取支付状态失败！");
        } catch (ServiceException e){
            throw e;
        } catch (Exception e){
            log.error("获取支付状态异常：{}", info.getId(), e);
            throw new ServiceException("获取支付状态失败！");
        }
    }

    @Override
    public boolean cancelPay(PayApply payApply) {
        YopRequest request = new YopRequest( "/rest/v1.0/trade/order/close", "POST");
        request.addParameter("parentMerchantNo", yeepayConfig.getMerchantNo());
        request.addParameter("merchantNo", yeepayConfig.getMerchantNo());
        request.addParameter("orderId", payApply.getId());
        request.addParameter("uniqueOrderNo", payApply.getOutTradeNo());
        try{
            YopResponse response = yeepayConfig.getClient().request(request);
            JSONObject json = JSON.parseObject(response.getStringResult());
            if("OPR00000".equalsIgnoreCase(json.getString("code"))){
                return true;
            }
            log.error("关闭订单异常! {} - {}", payApply.getId(), response.getStringResult());
            return false;
        }catch (Exception e){
            log.error("关闭订单异常! {}", payApply.getId(), e);
        }
        return false;
    }
}
